package com.wang.todoList.filter;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wang.todoList.constant.BaseConstant;
import com.wang.todoList.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截器
 * @author Zifan
 * @date 2021年07月10日20:42
 */
@Slf4j
public class BaseFilter implements HandlerInterceptor {

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("OPTIONS".equals(method)){
            return true;
        }
        //获取请求头
        String jwt = request.getHeader("Authorization");
        Map<Object, Object> errMap = new HashMap<>();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = null;
        //校验请求token是否正确或者是否过期
        try {
            if (JwtUtil.validationJwt(jwt)) {
                //根据密钥校验通过
                //下面判断是否过期
                if (JwtUtil.jwtIsLate(jwt)) {
                    //未失效
                    return true;
                }else {
                    //失效了
                    errMap.put("status", BaseConstant.REQUEST_NO_ACCESS);
                    errMap.put("msg","token已经过期");
                    out = response.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(errMap));
                    out.flush();
                    out.close();
                    return false;
                }
            }else {
                //校验失败
                errMap.put("status", BaseConstant.REQUEST_NO_ACCESS);
                errMap.put("msg","token校验失败");
                out = response.getWriter();
                out.write(new ObjectMapper().writeValueAsString(errMap));
                out.flush();
                out.close();
                return false;
            }
        }catch (Exception e){
            log.error(e.getMessage());
            errMap.put("status", BaseConstant.REQUEST_NO_ACCESS);
            errMap.put("msg","token无效");
            out = response.getWriter();
            out.write(new ObjectMapper().writeValueAsString(errMap));
            out.flush();
            out.close();
            return false;
        }finally {
            if (ObjectUtil.isNotNull(out)){
                out.flush();
                out.close();
            }
        }
        //如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作
    }
    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
